Code:
#include <stdio.h>
void reverse(char* string, int length) {
char otherString[length + 1];
for (int i = 0; i < length; i++) {
otherString[i] = string[length - i - 1];
}
otherString[length] = '\0';
for (int i = 0; i < length; i++) {
string[i] = otherString[i];
}
}
int main() {
//char* string = "ABCDE"; //this segfaults. Why?
char string[] = "ABCDE";
printf("Before: %s\n", string);
reverse(string, 5);
printf("After: %s\n", string);
return 0;
}
Besides the, most certainly, not very performant string reversal function, I'm confused with the differences between passing a string param to reverse it. If I declare it as string[], it works just fine. But if I declared it as char*, it segfaults. Why is it?
I welcome any resource that might document this further.